#include "DaemonThread.h"

#include <iostream>

#include "ThreadSafePrinter.h"

HTHREADPOOL_NAMESPACE_BEGIN

DaemonThread::DaemonThread(Task task)
    : ThreadObject(ThreadType::kDaemon), m_task(std::move(task)) {}

DaemonThread::~DaemonThread() {
    exit();
}

void DaemonThread::exit() { quit(); }

void DaemonThread::run() {
  while (true) {
    {
      std::unique_lock<std::mutex> lock(m_mutex);
      m_cv.wait(lock, [this] {
        return m_state.load() == ThreadState::kRunning ||
               m_state.load() == ThreadState::kTerminated;
      });

      if (m_state.load() == ThreadState::kTerminated) {
        break;
      }
    }

    try {
      // 安全打印日志
      ThreadSafePrinter threadSafePrinter;
      threadSafePrinter.print("DaemonThread thread running.......%d",
                              static_cast<int>(m_type));
      m_task(); // 执行任务
      std::this_thread::sleep_for(std::chrono::milliseconds(1));
    } catch (const std::exception &e) {
      // 捕获异常，避免线程崩溃
      std::cerr << "Task exception: " << e.what() << std::endl;
      break; // 可选：是否需要退出线程
    }
    std::this_thread::yield(); // 释放 CPU
  }
}

HTHREADPOOL_NAMESPACE_END
